console.info(baseUrl);
layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'"+date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds+"'";
        return currentdate;
    }
    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,
        done:function (value,dates) {
            dateMin.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            }
        }
    });
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;


    var tableIns = table.render({
        elem: '#callTaskList',
        url : baseUrl+'/linkageCall/queryCallTasks',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        },loading: true
        ,page: {
            limit: 10
            ,limits: [10, 20, 30, 40, 50]
            ,curr: 1
            ,groups: 5
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip','count']
        },
        cols : [[
            /*{type: "checkbox", fixed:"left", width:50 },*/
            {field: 'taskName', title: '资料包名称', width:350},
            {field: 'projectName', title: '联动项目', align:'center'},
            {field: 'newsStatus', title: '进度',  align:'center', valign:"middle",templet:"#newsStatus",templet:function (d) {
                return d.calledNum+"/"+d.callNum;
              /*  return '<div class="layui-progress" lay-showpercent="true" style="text-align: center;margin-top: 20px">\n' +
                    '                    <div class="layui-progress-bar layui-bg-red" lay-percent="' +d.calledNum+"/"+d.callNum +'" ' +
                    'style="width: ' +d.calledNum/d.callNum+ '">' +
                    '<span class="layui-progress-text">' +d.calledNum+"/"+d.callNum + '</span></div>\n' +
                    '</div>';*/
            }},
            {field: 'createUserName', title: '创建人', align:'center'},
            {field: 'createTime', title: '创建时间', align:'center', minWidth:110},
            {field: 'id', title: 'id', align:'center', minWidth:110},
            {title: '操作', width:170, templet:'#newsListBar',fixed:"right",align:"center"}
        ]],done: function(res, curr, count){
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
            console.log(res);
            //得到当前页码
            console.log(curr);
            //得到数据总量
            console.log(count);
            intTableColorChange();
            LayUIDataTable.SetJqueryObj($);// 第一步：设置jQuery对象
            LayUIDataTable.HideField('id');// 隐藏列-单列模式
            //LayUIDataTable.HideField(['num','match_guest']);// 隐藏列-多列模式
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
                console.log("当前页数据条数:" + currentRowDataList.length);
                console.log("当前行索引：" + index);
                console.log("触发的当前行单元格：" + currentData);
                console.log("当前行数据：" + JSON.stringify(rowData));
                console.log(rowData.id);
                /*var msg = '<div style="text-align: left"> 【当前页数据条数】' + currentRowDataList.length + '<br/>【当前行索引】' + index + '<br/>【触发的当前行单元格】' + currentData + '<br/>【当前行数据】' + JSON.stringify(rowData) + '</div>';
                 layer.msg(msg)*/
            });
        }
        ,text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });

    //是否置顶
    form.on('switch(newsTop)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            layer.close(index);
            if(data.elem.checked){
                layer.msg("置顶成功！");
            }else{
                layer.msg("取消置顶成功！");
            }
        },500);
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    function addTasks(edit){
        var index = layer.open({
            title : "创建云呼资料包",
            type : 2,
            content : [baseUrl+"/linkageCall/addLinkageCallTask"],
            resize:true,
            maxmin:false,
            isOutAnim:true,
            scrollbar:true,
            area : ['570px','330px'],
            success : function(layero, index){
                // layer.iframeAuto(index);
                var body = layer.getChildFrame('body', index);
                if(edit){
                    body.find(".newsName").val(edit.newsName);
                    body.find(".abstract").val(edit.abstract);
                    body.find(".thumbImg").attr("src",edit.newsImg);
                    body.find("#news_content").val(edit.content);
                    body.find(".newsStatus select").val(edit.newsStatus);
                    body.find(".openness input[name='openness'][title='"+edit.newsLook+"']").prop("checked","checked");
                    body.find(".newsTop input[name='newsTop']").prop("checked",edit.newsTop);
                    form.render();
                }
                setTimeout(function(){
                    layer.tips('点击此处返回管理列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        // layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        /*$(window).on("resize",function(){
            layer.full(index);
        })*/
    }
    $(".addTask_btn").click(function(){
        addTasks();
    });

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    });

    //列表操作
    table.on('tool(callTaskList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if(layEvent === 'edit'){ //编辑
            addNews(data);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此文章？',{icon:3, title:'提示信息'},function(index){
                // $.get("删除文章接口",{
                //     newsId : data.newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                    tableIns.reload();
                    layer.close(index);
                // })
            });
        } else if(layEvent === 'look'){ //预览
            layer.open({
                title : "查看任务详情",
                type : 2,
                content : [baseUrl+"/linkageCall/viewCallTaskDetail?callTaskId="+data.id],
                resize:true,
                maxmin:false,
                isOutAnim:true,
                scrollbar:true,
                area : ['947px', '775px'],
                success : function(layero, index){
                }
            });
        }
    });

    // 提交查询条件表单
    form.on('submit(query)', function(data){
        var load = layer.load();
        tableIns.reload({
            url : baseUrl+'/linkageCall/queryCallTasks'
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where: data.field
            ,done: function(res, curr, count){
                layer.close(load);

                // loadDataCallBack(res, curr, count);
            }
        });
    });

    //选中行时，高亮显示
    function intTableColorChange(){
        $(".layui-table-body tr").click(function(e){
            $(".layui-table-body  tr ").css("background","");
            $(this).css("background","#e6e6e6");
        });
    }

});